//
//  BKSearchView.m
//  lg_zhinengbeikao_english
//
//  Created by 盛超 on 2019/1/8.
//  Copyright © 2019年 zhukai. All rights reserved.
//

#import "BKSearchView.h"

@implementation BKSearchView

- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = rgba(245, 245, 245, 1);
        [self setupUI];
    }
    
    return self;
    
}

- (void)setupUI {
    
    UIView *bgView = [UIView new];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 15;
    bgView.layer.masksToBounds = YES;
    [self addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(13));
        make.right.equalTo(@(-13));
        make.centerY.equalTo(self).offset(3.5);
        make.height.mas_equalTo(30);
    }];
    
    UITextField *textFeild = [[UITextField alloc] init];
    NSMutableAttributedString *attrPlaceholder = [[NSMutableAttributedString alloc] initWithString:@"请输入内容关键字"];
    [attrPlaceholder addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13] range:NSMakeRange(0, attrPlaceholder.length)];
    textFeild.attributedPlaceholder = attrPlaceholder;
    textFeild.delegate = self;
    [bgView addSubview:textFeild];
    [textFeild mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@(15));
        make.right.equalTo(@(-15));
        make.top.bottom.equalTo(bgView);
    }];
    
    UIImageView *iconView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    iconView.image = [UIImage imageNamed:@"kz-放大镜"];
    textFeild.rightView = iconView;
    textFeild.rightViewMode = UITextFieldViewModeAlways;
    
}


#pragma mark - textFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    self.searchEndBlock(textField.text);
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
    if (range.length == 1 && string.length == 0) {
        return YES;
    }
    //so easy
    else if (textField.text.length >= 15) {
        textField.text = [textField.text substringToIndex:15];
        return NO;
    }
    
    return YES;
}

@end
